
package com.bidevalution.business.job;

import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.*;
import com.bidevalution.support.context.Constants;
import com.google.common.collect.Maps;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.OConvertUtils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @description: 商务标评审-主要材料评审计算
 * @author: xiayf
 * @date: 2019-10-15 14:05
 */
public class MainMaterialsNewJob implements StepJobJdbcFactory {

    private JdbcTemplateService jdbcTemplateService;

    @Override
    public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
        this.jdbcTemplateService = jdbcTemplateService;
    }

    private Logger log = LogManager.getLogger(getClass());

    @Override
    public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode, String expertId, String layouCode) throws Exception {
        try {
            Map<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("sectionStepId", beSectionStepJob.getSectionStepId());
            paramMap.put("submitCode", submitCode);
            paramMap.put("sectionId", beSectionStepJob.getSectionId());
            RowMapper<BeSectionInfo> rm = BeanPropertyRowMapper.newInstance(BeSectionInfo.class);
            BeSectionInfo beSectionInfo = jdbcTemplateService.selectForObject(" select td_projectId from be_section_info where seq_id=:sectionId ", paramMap, rm);
            paramMap.put("tdProjectId", beSectionInfo.getTdProjectid());
            String sqlStr = " SELECT a.enterprise_id enterpriseId,SUM(a.rightCount) rightCount FROM(  " +
                    "  SELECT tb.enterprise_id, " +
                    "  CASE WHEN (zb.bali_Code = tb.blfx_Code AND zb.bali_Name = tb.blfx_Name AND zb.bali_Spec = tb.blfx_Spec AND zb.bali_Unit = tb.blfx_Unit)   " +
                    "  THEN 1 ELSE 0 END AS rightCount  " +
                    "  FROM td_BasicList zb  " +
                    "  LEFT JOIN td_BasicListFX_Bid tb ON zb.bali_ProjectID=tb.blfx_ProjectID AND zb.bali_BasicListID=tb.blfx_BasicListID  " +
                    "  WHERE tb.blfx_ProjectID=:tdProjectId AND zb.bali_State='3'  " +
                    "  UNION ALL  " +
                    "  SELECT tb.enterprise_id,  " +
                    "  CASE WHEN (zb.bali_Code = tb.blfx_Code AND zb.bali_Name = tb.blfx_Name AND zb.bali_Spec = tb.blfx_Spec AND zb.bali_Unit = tb.blfx_Unit AND zb.bali_Price = tb.blfx_Price)   " +
                    "  THEN 1 ELSE 0 END AS rightCount  " +
                    "  FROM td_BasicList zb  " +
                    "  LEFT JOIN td_BasicListFX_Bid tb ON zb.bali_ProjectID=tb.blfx_ProjectID AND zb.bali_BasicListID=tb.blfx_BasicListID  " +
                    "  WHERE tb.blfx_ProjectID=:tdProjectId AND zb.bali_State IN('1','2')  " +
                    "  ) a  " +
                    "  GROUP BY a.enterprise_id";
            List<Map<String, Object>> enterList = jdbcTemplateService.selectForList(sqlStr, paramMap);
            //保存计算结果
            saveResult(paramMap, enterList);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new Exception("*****计算商务标评审-主要材料评审失败*****");
        }
    }

    private void saveResult(Map<String, Object> paramMap, List<Map<String, Object>> enterList) throws Exception {
        try {
            //查询招标材料要求数
            StringBuilder sb = new StringBuilder();
            sb.append(" SELECT enterprise_id enterpriseId,COUNT(bali_BasicListID) rightCount ");
            sb.append(" FROM td_bidinfo a LEFT JOIN td_BasicList b ON a.biin_ProjectID=b.bali_ProjectID ");
            sb.append(" WHERE bali_ProjectID=:tdProjectId ");
            sb.append(" GROUP BY enterprise_id ");
            List<Map<String, Object>> list = jdbcTemplateService.selectForList(sb.toString(), paramMap);
            if (list != null && !list.isEmpty()) {
                //招标要求材料数
                int count = OConvertUtils.getInt(list.get(0).get("rightCount"));
                List<BeComputerResult> beComputerResultList = new ArrayList<>();
                BeComputerResult beComputerResult = null;
                for (Map<String, Object> dataMap : list) {
                    beComputerResult = new BeComputerResult();
                    beComputerResult.setSeqId(IdsUtil.uuid());
                    beComputerResult.setSectionStepId(OConvertUtils.getString(paramMap.get("sectionStepId")));
                    beComputerResult.setSectionId(OConvertUtils.getString(paramMap.get("sectionId")));
                    beComputerResult.setEnterpriseId(OConvertUtils.getString(dataMap.get("enterpriseId")));
                    //招标要求材料数
                    beComputerResult.setC1(OConvertUtils.getString(count));
                    //投标单位一条都没有未响应则未响应数是要求数
                    int errorCount = count;
                    for (Map<String, Object> map : enterList) {
                        if (OConvertUtils.getString(dataMap.get("enterpriseId")).equals(OConvertUtils.getString(map.get("enterpriseId")))) {
                            //未响应材料数=招标要求材料数-投标响应材料数
                            errorCount = count - OConvertUtils.getInt(map.get("rightCount"));
                            break;
                        }
                    }
                    //未响应材料数
                    beComputerResult.setC2(OConvertUtils.getString(errorCount));
                    //是否通过
                    if (errorCount > Constants.ZERO) {
                        beComputerResult.setIsPassed(Constants.ZERO.toString());
                    } else {
                        beComputerResult.setIsPassed(Constants.ONE.toString());
                    }
                    beComputerResult.setCreateTime(DateUtil.now());
                    beComputerResultList.add(beComputerResult);
                }
                //批量转数组
                SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(beComputerResultList);
                //删除已存在结果
                jdbcTemplateService.update(" DELETE FROM be_computer_result WHERE section_id=:sectionId AND section_step_id =:sectionStepId ", paramMap);
                //批量插入
                jdbcTemplateService.bathInsert(" INSERT INTO be_computer_result(seq_id,section_step_id,section_id,enterprise_id,c1,c2,is_passed,create_time) " +
                        " VALUES(:seqId, :sectionStepId, :sectionId,:enterpriseId,:c1,:c2,:isPassed,:createTime) ", beanSources);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }
}

